package com.sgcc.operate.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.google.common.collect.Maps;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.security.service.TokenService;
import com.sgcc.operate.domain.OAttrField;
import com.sgcc.operate.domain.OCrowdAttr;
import com.sgcc.operate.domain.vo.AttrListDto;
import com.sgcc.operate.domain.vo.RuleAttrDto;
import com.sgcc.operate.mapper.OAttrFieldMapper;
import com.sgcc.operate.mapper.OCrowdAttrMapper;
import com.sgcc.operate.mapper.OPrizeCostMapper;
import com.sgcc.system.api.RemoteDictDataService;
import com.sgcc.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sgcc.operate.mapper.OCrowdRuleMapper;
import com.sgcc.operate.domain.OCrowdRule;
import com.sgcc.operate.service.IOCrowdRuleService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 人群规则定义Service业务层处理
 * 
 * @author sgcc
 * @date 2021-03-23
 */
@Service
public class OCrowdRuleServiceImpl implements IOCrowdRuleService 
{
    @Autowired
    private OCrowdRuleMapper oCrowdRuleMapper;
    @Autowired
    private OCrowdAttrMapper oCrowdAttrMapper;
    @Autowired
    private OAttrFieldMapper oAttrFieldMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RemoteDictDataService remoteDictDataService;
    @Autowired
    private OPrizeCostMapper oPrizeCostMapper;

    /**
     * 查询人群规则定义
     * 
     * @param id 人群规则定义ID
     * @return 人群规则定义
     */
    @Override
    public OCrowdRule selectOCrowdRuleById(String id)
    {
        OCrowdRule oCrowdRule = oCrowdRuleMapper.getDetailsByCrowdRuleId(id);
        List<RuleAttrDto> ruleAttrs = oCrowdRule.getRuleAttrs();
        if (null != ruleAttrs) {
            for (RuleAttrDto ruleAttr : ruleAttrs) {
                List<AttrListDto> attrs = ruleAttr.getAttrs();
                if (null != attrs) {
                    for (AttrListDto attr : attrs) {
                        getDictData(attr.getDatafieldcode(), attr.getDatafieldname(), attr.getCodeList());
                    }
                }
            }
        }
        return oCrowdRule;
    }


    private void getDictData(String dataFieldCode, String dataFieldName, List<Map<String, String>> codeList) {
        String[] codes = null, names = null;
        if (!StringUtils.isBlank(dataFieldCode)) {
            codes = dataFieldCode.split(",");
        }
        if (!StringUtils.isBlank(dataFieldName)) {
            names = dataFieldName.split(",");
        }
        if (codes != null && names != null) {
            Map<String, Object> result = adjustData(codes, names);
            String[] array1 = (String[]) result.get("array1");
            String[] array2 = (String[]) result.get("array2");
            for (int i = 0; i < array1.length; i ++) {
                Map<String, String> codeMap = Maps.newHashMap();
                codeMap.put(result.get("array1Mean").toString(), array1[i]);
                codeMap.put(result.get("array2Mean").toString(), array2[i]);
                codeList.add(codeMap);
            }
        }
    }

    private Map<String, Object> adjustData(String[] codes, String[] names) {
        Map<String, Object> result = Maps.newHashMap();
        if (codes.length != names.length) {
            if (codes.length > names.length) {
                result.put("array1", names);
                result.put("array1Mean", "label");
                result.put("array2", codes);
                result.put("array2Mean", "value");
            }
            if (codes.length < names.length) {
                result.put("array1", codes);
                result.put("array1Mean", "value");
                result.put("array2", names);
                result.put("array2Mean", "label");
            }
        } else {
            result.put("array1", codes);
            result.put("array1Mean", "value");
            result.put("array2", names);
            result.put("array2Mean", "label");
        }
        return result;
    }


    /**
     * 查询人群规则定义列表
     * 
     * @param oCrowdRule 人群规则定义
     * @return 人群规则定义
     */
    @Override
    public List<OCrowdRule> selectOCrowdRuleList(OCrowdRule oCrowdRule)
    {
        return oCrowdRuleMapper.selectOCrowdRuleList(oCrowdRule);
    }

    /**
     * 新增人群规则定义
     * 
     * @param oCrowdRule 人群规则定义
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOCrowdRule(OCrowdRule oCrowdRule)
    {
        LoginUser loginUser = tokenService.getLoginUser();
        oCrowdRule.setCreateDate(new Date());
        oCrowdRule.setUpdateDate(new Date());
        oCrowdRule.setCreateBy(loginUser.getUserid());
        oCrowdRule.setUpdateBy(loginUser.getUserid());
        oCrowdRule.setCrowdstatus("01");
        oCrowdRule.setModifyorg(loginUser.getSysUser().getDeptId());
        oCrowdRule.setDelFlag("0");

        R idstr = remoteDictDataService.getIdStr("same_day_id_create", "o_crow_rule_no");
        if (idstr.getCode() == 200) {
            oCrowdRule.setId(idstr.getData()+"");
            oCrowdRuleMapper.insertOCrowdRule(oCrowdRule);
        } else {
            return 0;
        }


        // 将所有del_flag='0'的记录标记为del_flag='2'
        oCrowdAttrMapper.signByCrowdRuleId(oCrowdRule.getId());
        for (RuleAttrDto ruleAttr : oCrowdRule.getRuleAttrs()) {
            // delFlag = 1直接删除
            if (OCrowdRule.DEL_FLAG_DELETE.equals(ruleAttr.getDelFlag())) {
                oCrowdAttrMapper.delSignByCrowdRuleId(oCrowdRule.getId(), ruleAttr.getRuleAttrId());
                continue;
            }
            // 与del_flag='2'的记录判断存在性
            if (oCrowdAttrMapper.judgeExist(ruleAttr.getRuleAttrId(), oCrowdRule.getId())) { // 存在，将del_flag设置为0
                oCrowdAttrMapper.restoreByCrowdRuleId(oCrowdRule.getId());
            }
            // 不存在插入，直接进入下一步
            for (AttrListDto attr : ruleAttr.getAttrs()) {
                OCrowdAttr oCrowdAttr = new OCrowdAttr();
                oCrowdAttr.setCrowdid(oCrowdRule.getId());
                oCrowdAttr.setAttrfieldid(attr.getAttrfieldid());
                oCrowdAttr.setRuleattrid(ruleAttr.getRuleAttrId());
                oCrowdAttr.setLowervalue(attr.getLowervalue());
                oCrowdAttr.setUppervalue(attr.getUppervalue());
                String crowdAttrId = oCrowdAttrMapper.getId(oCrowdRule.getId(), attr.getAttrfieldid(), ruleAttr.getRuleAttrId());
                if (StringUtils.isBlank(crowdAttrId)) {
                    String id= UUID.randomUUID().toString().replaceAll("-", "");
                    oCrowdAttr.setId(id);
                    oCrowdAttr.setCreateBy(loginUser.getUserid());
                    oCrowdAttr.setCreateDate(new Date());
                    oCrowdAttr.setUpdateBy(loginUser.getUserid());
                    oCrowdAttr.setUpdateDate(new Date());
                    oCrowdAttr.setDelFlag("0");
                    oCrowdAttrMapper.insertOCrowdAttr(oCrowdAttr);
                } else {
                    oCrowdAttr.setId(attr.getCrowdattrid());
                    oCrowdAttr.setUpdateBy(loginUser.getUserid());
                    oCrowdAttr.setUpdateDate(new Date());
                    oCrowdAttrMapper.updateOCrowdAttr(oCrowdAttr);
                }
            }
        }

        return 1;
    }

    /**
     * 修改人群规则定义
     * 
     * @param oCrowdRule 人群规则定义
     * @return 结果
     */
    @Override
    public int updateOCrowdRule(OCrowdRule oCrowdRule)
    {
        LoginUser loginUser = tokenService.getLoginUser();
        oCrowdRule.setUpdateDate(new Date());
        oCrowdRule.setUpdateBy(loginUser.getUserid());
        oCrowdRuleMapper.updateOCrowdRule(oCrowdRule);


        // 将所有del_flag='0'的记录标记为del_flag='2'
        oCrowdAttrMapper.signByCrowdRuleId(oCrowdRule.getId());
        for (RuleAttrDto ruleAttr : oCrowdRule.getRuleAttrs()) {
            // delFlag = 1直接删除
            if (OCrowdRule.DEL_FLAG_DELETE.equals(ruleAttr.getDelFlag())) {
                oCrowdAttrMapper.delSignByCrowdRuleId(oCrowdRule.getId(), ruleAttr.getRuleAttrId());
                continue;
            }
            // 与del_flag='2'的记录判断存在性
            if (oCrowdAttrMapper.judgeExist(ruleAttr.getRuleAttrId(), oCrowdRule.getId())) { // 存在，将del_flag设置为0
                oCrowdAttrMapper.restoreByCrowdRuleId(oCrowdRule.getId());
            }
            // 不存在插入，直接进入下一步
            for (AttrListDto attr : ruleAttr.getAttrs()) {
                OCrowdAttr oCrowdAttr = new OCrowdAttr();
                oCrowdAttr.setCrowdid(oCrowdRule.getId());
                oCrowdAttr.setAttrfieldid(attr.getAttrfieldid());
                oCrowdAttr.setRuleattrid(ruleAttr.getRuleAttrId());
                oCrowdAttr.setLowervalue(attr.getLowervalue());
                oCrowdAttr.setUppervalue(attr.getUppervalue());
                String crowdAttrId = oCrowdAttrMapper.getId(oCrowdRule.getId(), attr.getAttrfieldid(), ruleAttr.getRuleAttrId());
                if (StringUtils.isBlank(crowdAttrId)) {
                    String id= UUID.randomUUID().toString().replaceAll("-", "");
                    oCrowdAttr.setId(id);
                    oCrowdAttr.setCreateBy(loginUser.getUserid());
                    oCrowdAttr.setCreateDate(new Date());
                    oCrowdAttr.setUpdateBy(loginUser.getUserid());
                    oCrowdAttr.setUpdateDate(new Date());
                    oCrowdAttrMapper.insertOCrowdAttr(oCrowdAttr);
                } else {
                    oCrowdAttr.setId(attr.getCrowdattrid());
                    oCrowdAttr.setUpdateBy(loginUser.getUserid());
                    oCrowdAttr.setUpdateDate(new Date());
                    oCrowdAttrMapper.updateOCrowdAttr(oCrowdAttr);
                }
            }
        }
        return 1;
    }

    /**
     * 批量删除人群规则定义
     * 
     * @param ids 需要删除的人群规则定义ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteOCrowdRuleByIds(String[] ids)
    {
        oPrizeCostMapper.deleteOPrizeCostByActiIds(ids);
        return oCrowdRuleMapper.deleteOCrowdRuleByIds(ids);
    }

    /**
     * 删除人群规则定义信息
     * 
     * @param id 人群规则定义ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteOCrowdRuleById(String id)
    {
        oCrowdRuleMapper.deleteOCrowdRuleById(id);
        oPrizeCostMapper.deleteOPrizeCostByActiId(id);
        return 1;
    }

    @Override
    public boolean judgeName(String id, String rulename) {
        return oCrowdRuleMapper.judgeName(id,rulename);
    }
    @Override
    public List<OAttrField> getFieldByRuleAttrId(String ruleAttrId) {
        List<OAttrField> attrs = oAttrFieldMapper.getFieldByRuleAttrId(ruleAttrId);
        for (OAttrField attr : attrs) {
            getDictData(attr.getDatafieldcode(), attr.getDatafieldname(), attr. getCodeList());
        }
        return attrs;
    }
}
